package utils
{
	import mx.collections.XMLListCollection;
	import mx.rpc.AsyncResponder;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.utils.ObjectUtil;
	
	import framework.AppGlobal;

	public class XMLUtil
	{
		/**
		 * 加载远程XML
		 * @param p_path
		 * @param p_callback
		 * @return
		 */
		public static function loadXML(p_path:String, p_callback:Function):void
		{
			if(p_path.indexOf("http://") < 0)
				p_path = AppGlobal.contextRoot + p_path;
			var hs:HTTPService = new HTTPService();
			hs.url = p_path;
			hs.showBusyCursor = true;
			hs.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
			var token:AsyncToken = hs.send();
			token.addResponder(new AsyncResponder(loadResultHandler, 
				loadFaultHandler, token));
			
			function loadResultHandler(p_result:ResultEvent, p_token:AsyncToken):void
			{
				if(p_callback != null)
					p_callback(new XML(p_result.result));
			}
			
			function loadFaultHandler(p_fault:FaultEvent, p_token:AsyncToken):void
			{
				trace("load xml fail!" + p_fault.fault.faultString);
			}
		}
		
		/**
		 * 将XML转换成标记式数组（节点名不能重复）
		 */
		public static function XMLToObject(p_xml:XML):Object
		{
			var obj:Object = {};
			var xlc:XMLListCollection = new XMLListCollection(p_xml.children());
			xlc.addAll(new XMLListCollection(p_xml.attributes()));
			for(var i:int = 0;i < xlc.length;i++){
				var xml:XML = xlc.getItemAt(i) as XML;
				if(xml.hasComplexContent()){
					obj[String(xml.name())] = XMLToObject(xml);
				}else{
					obj[String(xml.name())] = String(xml.valueOf());
				}
			}
			return obj;
		}
		
		/**
		 * 将XML转换成某种类型的VO
		 */
		public static function convertXMLToClass(p_xml:XML, p_type:Class):Object
		{
			var target:Object = new p_type;
			var objInfo:Object = mx.utils.ObjectUtil.getClassInfo(p_xml);
			var fieldName:Array = objInfo["properties"] as Array;
			for each (var q:QName in fieldName)
			{
				var attribute:String = q.localName.toString();
				var prop:String = attribute.replace("@", "");
				if(target.hasOwnProperty(prop))
					target[prop] = p_xml[attribute].toString();
			}
			return target;
		}
	}
}